import java.util.*;

/**
 * @author LKQ
 * @date 2021/12/11 11:36
 * @description 迭代算法
 */
public class Solution2 {
    public static void main(String[] args) {
        TreeNode leaf7 = new TreeNode(7);
        TreeNode leaf5 = new TreeNode(5, null, leaf7);
        TreeNode leaf4 = new TreeNode(4, leaf5, null);
        TreeNode leaf3 = new TreeNode(3, null, leaf4);
        TreeNode leaf2 = new TreeNode(2, leaf3, null);
        TreeNode root = new TreeNode(1, leaf2, null);
        Solution2 solution2 = new Solution2();
        solution2.postorderTraversal(root);
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            // 最左节点
            root = stack.pop();
            if (root.right == null || root.right == prev) {
                // 最左节点的右节点是否为空，
                res.add(root.val);
                prev = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
}
